package widget.nest;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;

import java.lang.ref.WeakReference;

import widget.slide.SliderLayout;
import widget.utils.TouchUtils;


/**
 * Created by Mr.Fan on 2016-6-1.
 */
public class NestedViewPager extends ViewPager {
    private WeakReference<SliderLayout> reference;
    private boolean scrollerEnable = true;

    public NestedViewPager(Context context) {
        super(context);
        init();
    }

    public NestedViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        setOverScrollMode(OVER_SCROLL_NEVER);
        requestDisallowInterceptTouchEvent(true);
    }

    @Override
    public void setAdapter(PagerAdapter adapter) {
        super.setAdapter(adapter);
    }

    private TouchUtils.MoveListener moveListener = new TouchUtils.MoveListener();

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        SliderLayout SliderLayout = reference != null ? reference.get() : null;
        if (SliderLayout == null)
            return super.dispatchTouchEvent(ev);

        final int index = getCurrentItem();
        moveListener.onTouch(ev);
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                SliderLayout.setDraggable(false);
                break;
            case MotionEvent.ACTION_MOVE:
                if (index == 0 && !SliderLayout.isDraggable() && moveListener.isMoveRight()) {
                    SliderLayout.setDraggable(true);
                    return false;
                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                SliderLayout.setDraggable(true);
            default:
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return scrollerEnable ? super.onInterceptTouchEvent(ev) : false;
    }

    public void bindSliderLayout(SliderLayout SliderLayout) {
        reference = new WeakReference<>(SliderLayout);
    }

    public boolean isScrollerEnable() {
        return scrollerEnable;
    }

    public void setScrollerEnable(boolean scrollerEnable) {
        this.scrollerEnable = scrollerEnable;
    }
}
